package com.carl.study;

import com.carl.study.gen.tables.Person;
import com.carl.study.gen.tables.records.PersonRecord;
import com.carl.study.jooq.doc.PersonDoc;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.apache.commons.codec.binary.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;


/**
 * @program: FrameStudy
 * @description:
 * @author: Mr.Carl
 **/
public class MongoDBClient {


    public static String URI = "mongodb://root:root@192.168.2.11:27017/study";
    public static String PERSON = "person";




    public static void main(String[] args){

        //连接
        MongoClient mongoClient = new MongoClient(new MongoClientURI(URI));
        MongoDatabase database = mongoClient.getDatabase("study");
        MongoCollection<Document> collection = database.getCollection(PERSON);
//        Document person = new Document("name","zhangsan")
//                .append("sex","男")
//                .append("age","12")
//                .append("address","ada");
//        //添加
//        collection.insertOne(person);
        //查找
        FindIterable<Document> result = collection.find(new Document("name","zhangsan"));
        //FindIterable<Document> documents = collection.find();//返回集合中所有
        //collection.find(filter);//查询指定
        for (Document document : result) {
            PersonRecord record = new PersonRecord();
            record.setName(document.getString("name"));
            record.setSex(document.getString("sex"));
            record.setAge(Integer.parseInt(document.getString("age")));
            record.setAddress(document.getString("address"));
            System.out.println(record.toString());
        }
        //修改过滤器
        Bson filter = Filters.eq("name", "zhangsan");
        //修改单个文档 updateMany//修改所有匹配的
        collection.updateOne(filter, new Document("$set", new Document("age", 100)));
        //删除一个 deleteMany(filter)//删除所有匹配的
        collection.deleteOne(filter);

        mongoClient.close();

    }

}
